|
An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function. This pattern has been referred to as a self-executing anonymous function, but Ben Alman introduced the term IIFE as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.〔 == Usage == Immediately-invoked function expressions may be written in a number of different ways, although a common convention is to enclose both the function expression and invocation in parentheses. (function() )(); Passing variables into the scope is done as follows: (function(a, b) )('hello', 'world'); An initial parenthesis is one case where the automatic semicolon insertion (ASI) in JavaScript can cause problems; the expression is instead interpreted as a call to the last term on the preceding line. In some styles that omit optional semicolons, the semicolon is placed ''in front'' of the parenthesis, and is known as a defensive semicolon.〔"(JavaScript Semicolon Insertion: Everything you need to know )", Friday, May 28, 2010〕〔"(Semicolons in JavaScript are optional )", by Mislav Marohnić, 07 May 2010〕 For example: a = b + c ;(function() )(); ...to avoid being parsed as c(...) .抄文引用元・出典: フリー百科事典『 ウィキペディア(Wikipedia)』 ■ウィキペディアで「Immediately-invoked function expression」の詳細全文を読む スポンサード リンク
|